package com.book.servlet.action;

import com.book.entity.Book;
import com.book.entity.Student;
import com.book.entity.User;
import com.book.service.BookService;
import com.book.service.BorrowService;
import com.book.service.StudentService;
import com.book.service.impl.BookServiceImpl;
import com.book.service.impl.BorrowServiceImpl;
import com.book.service.impl.StudentServiceImpl;
import com.book.utils.ThymeleafUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.thymeleaf.context.Context;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

@WebServlet("/add-borrow")
public class AddBorrowServlet extends HttpServlet {
    BookService bookService;
    StudentService studentService;
    BorrowService borrowService;

    @Override
    public void init() throws ServletException {
        bookService = new BookServiceImpl();
        studentService = new StudentServiceImpl();
        borrowService = new BorrowServiceImpl();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Context context = new Context();
        List<Student> students = studentService.listStudents();
        List<Book> books = bookService.listExistBooks();
        User user = (User)req.getSession().getAttribute("user");
        if(req.getSession().getAttribute("warning") != null){
            // 将session中warning标志传递到context
            context.setVariable("warning", req.getSession().getAttribute("warning"));
            req.getSession().removeAttribute("warning");
        }
        if (req.getSession().getAttribute("incorrect")!=null){
            // 将session中incorrect标志传递到context
            context.setVariable("incorrect", 1);
            req.getSession().removeAttribute("incorrect");
        }
        if(req.getSession().getAttribute("noId") != null){
            // 将session中noId标志传递到context
            context.setVariable("noId", req.getSession().getAttribute("noId"));
            req.getSession().removeAttribute("noId");
        }
        context.setVariable("students", students);
        context.setVariable("books", books);
        context.setVariable("nickName", user.getNickname());
        ThymeleafUtil.process("add_borrow.html", context, resp.getWriter());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String bookName = req.getParameter("bookName");
        String studentName = req.getParameter("studentName");
        if(!bookName.isEmpty() && !studentName.isEmpty()){
            // 判断提交的表单不为空
            try{
                // 判断提交的信息是否合法
                int bookId = Integer.valueOf(bookName.split("-")[0]);
                int studentId = Integer.valueOf(studentName.split("-")[0]);
                if(bookService.selectBookById(Integer.valueOf(bookId))!=null  &&
                        studentService.getById(Integer.valueOf(studentId))!=null){
                    // 判断书籍和学生存在
                    if(bookService.getNumberById(Integer.valueOf(bookId))>0){
                        // 判断该书数量>0
                        borrowService.insertBorrow(LocalDateTime.now(), Integer.valueOf(bookId), Integer.valueOf(studentId));  // 插入借阅记录
                        bookService.minusBookNumber(Integer.valueOf(bookId));  // 根据id，书数量-1
                        resp.sendRedirect("index");
                        return;
                    }else {
                        req.getSession().setAttribute("warning", 1);  // 向session中添加书籍数量为0警告
                    }
                }else {
                    req.getSession().setAttribute("incorrect", 1);  // 向session中添加输入不合法标志
                }
            }catch (Exception e){
                req.getSession().setAttribute("incorrect", 1);  // 向session中添加输入不合法标志
            }
        }else {
            req.getSession().setAttribute("noId", 1);  // 向session中添加无Id标志
        }
        resp.sendRedirect("add-borrow");
    }
}